package com.xiangxiangjd.kj.papersstar.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangxiangjd.kj.papersstar.bean.*;
import com.xiangxiangjd.kj.papersstar.bean.result.ResultPage;
import com.xiangxiangjd.kj.papersstar.controller.entity.ApiCode;
import com.xiangxiangjd.kj.papersstar.controller.helper.$;
import com.xiangxiangjd.kj.papersstar.controller.model.ApiResultModel;
import com.xiangxiangjd.kj.papersstar.mapper.QuestionnaireMapper;
import com.xiangxiangjd.kj.papersstar.service.QuestionnaireService;
import com.xiangxiangjd.kj.papersstar.service.QuestionnaireUserService;
import com.xiangxiangjd.kj.papersstar.service.UserAnswerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 肖守凯
 * @since 2021-01-21
 */
@Service
@Slf4j
public class QuestionnaireServiceImpl extends ServiceImpl<QuestionnaireMapper, Questionnaire> implements QuestionnaireService {

    @Autowired
    private QuestionnaireUserService questionnaireUserService;
    @Autowired
    private UserAnswerService userAnswerService;

    /**
     * 添加Questionnaire
     *
     * @param questionnaire 前端传进的参数
     * @return 返回统一信息
     */
    @Override
    public ApiResultModel addQuestionnaire(Questionnaire questionnaire) {

        if (this.save(questionnaire)) {
            return $.success();
        } else {
            return $.error("添加失败");
        }
    }

    /**
     * 编辑跳转页面的回显数据Questionnaire
     *
     * @param id 前端传进的参数
     * @return 返回实体类
     */
    @Override
    public Questionnaire selectQuestionnaireByIdQuestionnaire(String id) {
        return this.getById(id);
    }


    /**
     * 编辑Questionnaire
     *
     * @param questionnaire 前端传进的参数
     * @return 返回统一信息
     */
    @Override
    public ApiResultModel editQuestionnaire(Questionnaire questionnaire) {
        if (this.updateById(questionnaire)) {
            return $.success();
        } else {
            return $.error("编辑失败");
        }
    }

    /**
     * 删除一条Questionnaire
     *
     * @param ids 前端传进的ID
     * @return 返回统一信息
     */
    @Override
    public ApiResultModel delQuestionnaires(List ids) {

        int i = baseMapper.deleteBatchIds(ids);

        return $.success(i);

    }

    /**
     * 分页查询Questionnaire
     *
     * @param page          页码
     * @param limit         查几条
     * @param questionnaire 前端传进的参数
     * @return 返回统一分页信息
     */
    @Override
    public ResultPage findQuestionnaireByPage(Integer page, Integer limit, Questionnaire questionnaire) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("page", (page - 1) * limit);
        paramMap.put("limit", limit);
        paramMap.put("questionnaire", questionnaire);
        List<Questionnaire> list = baseMapper.selectMyPage(paramMap);
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<Questionnaire> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

    @Override
    public Questionnaire getQuestionnaire(String questionnaireId) {
        return baseMapper.getQuestionnaire(questionnaireId);
    }


    @Override
    @Transactional
    public ApiResultModel submitQuestionnaire(QuestionnaireUser questionnaireUser) {
        log.info("用户提交了调查问卷:" + questionnaireUser.toString());
        if (questionnaireUser.getUUserId() == null) return $.error("请填写用户id");
        if (questionnaireUser.getQuestionnaireId() == null) return $.error("请选择问卷");
        //查询问卷是否填写过
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("u_user_id", questionnaireUser.getUUserId());
        queryWrapper.eq("questionnaire_id", questionnaireUser.getQuestionnaireId());
        QuestionnaireUser oneQuestionnaireUser = questionnaireUserService.getOne(queryWrapper);
        if (oneQuestionnaireUser != null) {
            throw new RuntimeException("该用户已填写该问卷");
        }
        //      $.error("该用户已填写该问卷!");
        //保存问卷
        boolean save = questionnaireUserService.save(questionnaireUser);


        if (!save) throw new RuntimeException("提交失败 请重新提交 !");
        //获取所有填写的答案
        List<UserAnswer> userAnswers = questionnaireUser.getUserAnswers();
        log.info("userAnswers:" + userAnswers.toString());
        //获取问卷的所有详情
        Questionnaire questionnaire = baseMapper.getQuestionnaire(questionnaireUser.getQuestionnaireId());
        //获取问卷的所有题型
        List<Topic> topics = questionnaire.getTopics();
        //存入所有的问题  ID 为KEY
        Map<String, Topic> map = new HashMap<>();
        topics.forEach((obj) -> map.put(obj.getId(), obj));
        log.info("map:" + map.toString());
        //如果是调查类型
        if (questionnaire.getQuestionnaireType().equalsIgnoreCase("1")) {
            //处理调查类型
            int topicsSize = topics.size(); //问卷 题目个数
            int userAnswersSize = userAnswers.size();//用户回答的
            if (userAnswersSize != topicsSize)
                throw new RuntimeException("还有" + (topicsSize - userAnswersSize) + "题未作答!");
            //用户记录用户的
            int best = 0;  //最好值
            int worst = 0; //最差值
            //遍历用户的答案 对比答案
            for (int i = 0; i < userAnswers.size(); i++) {
                log.info("userAnswers.get(i).getTopicId():" + userAnswers.get(i).getTopicId());
                //获取一个问题 MAP
                Topic topic = map.get(userAnswers.get(i).getTopicId());
                log.info("topic:" + topic);
                if (topic == null) throw new RuntimeException("回答出现问题 请联系管理员!" + userAnswers.get(i).getTopicId());
                //获取所有的答案
                List<Answer> answers = topic.getAnswers();
                //问题不存在
                //查询答案质量
                for (int j = 0; j < answers.size(); j++) {
                    if (answers.get(j).getId().equals(userAnswers.get(i).getanswerId())) {
                        String answerOrder = answers.get(j).getAnswerOrder();

                        if (answerOrder.equals("1")) {
                            best++;
                            continue;
                        }//最好值++
                        else if (answerOrder.equals(String.valueOf(answers.size()))) {
                            worst++;
                            continue;
                        } //最差值++
                    }
                }
            }
            System.out.println("best:" + best);
            System.out.println("worst:" + worst);
            if (best == 0) throw new RuntimeException("最少有一个最好值");
            if (worst == 0) throw new RuntimeException("最少有一个最差值");
        }

        userAnswers.forEach((user) -> user.setQuestionnaireUserId(questionnaireUser.getId()));


        boolean b = userAnswerService.saveBatch(userAnswers);
        if (!b) throw new RuntimeException("提交失败 服务器出现问题 请稍后重试!");
        return $.success(ApiCode.success, ApiCode.success_msg, "提交成功");
    }

    @Override
    public Questionnaire getQuestionnaireAnswered(String questionnaireId) {
        return baseMapper.getQuestionnaireAnswered(questionnaireId);
    }


}
